<template>
  <div>
    <Row>
      <Card shadow>
        <div ref="dom" v-if="showChartpie" style="height:310px"></div>
      </Card>
    </Row>
    <Row :gutter="20" style="margin-top: 10px">
      <i-col :md="24" :lg="8" style="margin-bottom: 20px">
        <Card shadow>
          <chart-pie v-if="showChartpie" style="height: 300px" :value="pieData" text="用户消费占比情况"></chart-pie>
        </Card>
      </i-col>
      <i-col :md="24" :lg="16" style="margin-bottom: 20px">
        <Card shadow>
          <chart-bar style="height: 300px" v-if="showChartpie" :value="useDataBar"
            :text="new Date().getFullYear() + '年用户每月消费占比柱状图'" />
        </Card>
      </i-col>
    </Row>
    <Row :gutter="20" style="margin-top: 10px">

      <i-col :md="24" :lg="16" style="margin-bottom: 20px">
        <Card shadow>
          <chart-bar style="height: 300px" v-if="showChartpie" :value="incomeDataBar"
            :text="new Date().getFullYear() + '年用户每月收入占比柱状图'" />
        </Card>
      </i-col>
      <i-col :md="24" :lg="8" style="margin-bottom: 20px">
        <Card shadow>
          <chart-pie v-if="showChartpie" style="height: 300px" :value="pieData" text="用户消费占比情况"></chart-pie>
        </Card>
      </i-col>
    </Row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { on, off } from "@/libs/tools";
import InforCard from "_c/info-card";
import CountTo from "_c/count-to";
import { ChartPie, ChartBar } from "_c/charts";
import { getAccountingData } from "@/api/content/accounting/consume.js";
import { getIncomeData } from "@/api/content/accounting/income.js";
export default {
  name: "home",
  components: {
    InforCard,
    CountTo,
    ChartPie,
    ChartBar
  },
  data() {
    return {
      dom: null,
      pieData: [
        { value: 0, name: "" },
        { value: 0, name: "" },
        { value: 0, name: "" },
        { value: 0, name: "" },
        { value: 0, name: "" },
        { value: 0, name: "" },
      ],
      useDataBar: {},
      incomeDataBar: {},
      useData: [],
      incomeData: [],
      showChartpie: false
    };
  },
  methods: {
    resize() {
      this.dom.resize();
    },
    //可以将数字转换成中文大写的表示，处理到万级别，例如 toChineseNum(12345)，返回 一万二千三百四十五。
    toChinesNum(num) {
      let changeNum = [
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九"
      ]; //changeNum[0] = "零"
      let unit = ["", "十", "百", "千", "万"];
      num = parseInt(num);
      let getWan = temp => {
        let strArr = temp
          .toString()
          .split("")
          .reverse();
        let newNum = "";
        for (var i = 0; i < strArr.length; i++) {
          newNum =
            (i == 0 && strArr[i] == 0
              ? ""
              : i > 0 && strArr[i] == 0 && strArr[i - 1] == 0
                ? ""
                : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) +
            newNum;
        }
        return newNum;
      };
      let overWan = Math.floor(num / 10000);
      let noWan = num % 10000;
      if (noWan.toString().length < 4) noWan = "0" + noWan;
      return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
    },
    getData() {
      const dateObj = new Date();
      let nowYear = dateObj.getFullYear(),
        //当前月份
        nowMonth = dateObj.getMonth() + 1,
        //当前天数
        nowDay = dateObj.getDate();

      // nowMonth = 8
      // nowDay = 31
      getAccountingData().then(res => {
        if (res.data.code == 0) {
          //卡片数量
          this.useData = res.data.data;
          //扇形统计图
          this.filterData = this.useData.filter(item => {
            return parseFloat(item.money) <= 200;
          });
          //扇形统计图
          let accountingType = ["超市", "网购", "餐饮", "交通", "门票", "住房"];
          for (let index = 0; index < accountingType.length; index++) {
            let item = this.useData.filter(data => {
              return data.name == accountingType[index];
            });
            let itemLength = item.length;
            let itemValue = 0;
            for (let i = 0; i < itemLength; i++) {
              itemValue += parseFloat(item[i].money);
            }
            this.pieData[index].value = parseInt(itemValue);
            this.pieData[index].name = accountingType[index];
          }


          //柱形统计图
          for (let index = 1; index <= 12; index++) {
            let item = this.useData.filter(data => {
              return (
                data.date.indexOf(nowYear) !== -1 &&
                parseInt(data.date.charAt(5) + data.date.charAt(6)) == index
              );
            });
            let num = 0;
            for (let i = 0, len = item.length; i < len; i++) {
              if (item[i]) {
                num += parseInt(item[i].money);
              }
            }
            if (num != 0) {
              this.useDataBar[index] = num;

            }
          }

          //折线统计图
          let option = {
            title: {
              text: this.toChinesNum(nowMonth) + "月每日消费折线统计图",
              subtext: "",
              x: "center",
              textStyle: {
                color: "#516b91"
              }
            },
            //鼠标放上去的提示
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "cross",
                label: {
                  backgroundColor: "#6a7985"
                }
              }
            },
            //定位布局
            grid: {
              top: "20%",
              left: "1.2%",
              right: "1%",
              bottom: "3%",
              containLabel: true
            },
            xAxis: [
              {
                type: "category",
                boundaryGap: false,
                data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
              }
            ],
            yAxis: [
              {
                type: "value"
              }
            ],
            series: [
              {
                name: "消费金额",
                type: "line",
                stack: "总量",
                label: {
                  normal: {
                    show: true,
                    position: "top",
                    fontSize: 10
                  }
                },
                areaStyle: {
                  normal: {
                    color: "#398DBF"
                  }
                },
                data: []
              }
            ]
          };
          //消费折现统计图横轴日期
          const showCount = nowDay;

          let newData = this.filterData.filter(item => {
            let day = parseInt(item.date.charAt(8) + item.date.charAt(9));
            return (
              item.date.indexOf(nowYear) != -1 &&
              day > nowDay - showCount &&
              day <= nowDay
            );
          });
          // for (
          //   let index = 0, len = this.useData.length;
          //   index < len;
          //   index++
          // ) {
          //   let day = parseInt(
          //     this.useData[index].date.charAt(8) +
          //       this.useData[index].date.charAt(9)
          //   );
          //   if (
          //     this.useData[index].date.indexOf(nowYear) == 0 &&
          //     day > nowDay - 7 &&
          //     day <= nowDay
          //   ) {
          //     newData.push(this.useData[index]);
          //   }
          // }
          let accountingArr = [],
            dayArr = [];
          for (let index = 0; index < showCount; index++) {
            let itemData = newData.filter(data => {
              let day = parseInt(data.date.charAt(8) + data.date.charAt(9));
              let month = parseInt(data.date.charAt(5) + data.date.charAt(6));
              return (
                data.date.indexOf(nowYear) !== -1 &&
                day == nowDay - index &&
                month == nowMonth
              );
            });
            let historyDay = nowDay - index;
            let num = 0;
            for (let i = 0, len = itemData.length; i < len; i++) {
              num += parseFloat(itemData[i].money);
            }
            accountingArr.unshift(parseInt(num));
            dayArr.unshift(nowMonth + "月" + historyDay + "日");
          }
          option.series[0].data = accountingArr;
          option.xAxis[0].data = dayArr;

          this.showChartpie = true;
          this.$nextTick(() => {
            this.dom = echarts.init(this.$refs.dom);
            this.dom.setOption(option);
            on(window, "resize", this.resize);
          });
        } else if (res.data.code == 1010) {
          this.$router.push("/login");
          this.$Message.warning("您的登录状态已失效，请您重新登录.");
        } else {
          this.$Message.error("出错了，错误原因：" + res.data.msg);
        }
      });
      getIncomeData().then(res => {
        this.incomeData = res.data.data
        for (let index = 1; index <= 12; index++) {
          let item = this.incomeData.filter(data => {
            return (
              data.date.indexOf(nowYear) !== -1 &&
              parseInt(data.date.charAt(5) + data.date.charAt(6)) == index
            );
          });
          let num = 0;
          for (let i = 0, len = item.length; i < len; i++) {
            if (item[i]) {
              num += parseInt(item[i].money);
            }
          }
          if (num != 0) {
            this.incomeDataBar[index] = num;
          }
        }
      })
    }
  },
  created() {
    this.getData();
  },
  mounted() { },
  beforeDestroy() {
    off(window, "resize", this.resize);
  }
};
</script>

<style lang="less" scope>
.count-style {
  font-size: 50px;
}

.zhu {
  color: #a2a2a2;
  font-size: 14px;
}

.ivu-card-body {
  padding: 10px 20px;
}
</style>
